package cn.com.hhrcw.login;

import cn.com.hhrcw.constant.CommonConstant;
import cn.com.hhrcw.entity.*;
import cn.com.hhrcw.service.*;
import cn.com.hhrcw.thirdLogin.vo.ThridLoginVO;
import cn.com.hhrcw.utils.Constant;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.utils.UuidUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 手机验证码登录
 *
 * @author lixingxing
 */
@Slf4j
public class MobileCodeLogin extends AbstractLogin<SysUser> {
    @Value("${spring.profiles.active}")
    private String profiles;

    /**
     * 测试环境
     */
    private static final String TEST_2 = "test2";

    @Autowired
    private ISysUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IPiInfoService piInfoService;

    @Autowired
    private ICvResumeService cvResumeService;

    @Autowired
    private IEnInfoService enInfoService;

    @Autowired
    ISysUserDepartService userDepartService;

    private final LoginVO vo;

    /**
     * 第三方登录、绑定时用的token
     */
    private String loginToken;

    /**
     * thirdToken 类型：bind-绑定登录 login-登录
     */
    private String loginType;

    public void setLoginToken(String loginToken) {
        this.loginToken = loginToken;
    }

    public void setLoginType(String loginType) {
        this.loginType = loginType;
    }

    public MobileCodeLogin(String username, String password, LoginVO vo) {
        super(username, password);
        this.vo = vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object login() {

        log.info("==========>[个人端]登录处理，username={},password={},loginType={}，loginToken={}", username, password, loginType, loginToken);
        SysUser member = null;
        ThridLoginVO t = null;
        //微信扫描登录成功时的处理
        if (StrUtil.equalsIgnoreCase(Constant.LOGIN_TYPE_WX_LOGIN_SUCESS, this.loginType) || StrUtil.equalsIgnoreCase(Constant.LOGIN_TYPE_KEEPALIVE, this.loginType)) {
            log.info("==========>微信扫描登录、保活登录 处理逻辑 loginType={}，thirdToken={}", loginType, loginToken);
            t = (ThridLoginVO) redisTemplate.opsForValue().get(loginToken);
            Assert.notNull(t, "登录超时异常，请重新扫描登录");
            member = userService.lambdaQuery().eq(SysUser::getId, t.getUserId()).eq(SysUser::getDelFlag, false).one();
            this.username = member.getPhone();
            this.password = null;
        } else {
            log.info("==========>手机号、验证码登录处理逻辑");
            member = userService.lambdaQuery().eq(SysUser::getPhone, username).eq(SysUser::getDelFlag, false).one();
        }

        if (member == null) {
            String substring = UuidUtils.getUUID().substring(0, 32);
            member = new SysUser();
            member.setId(substring);
            member.setPhone(username);
            member.setUsername(username);
            String salt = RandomStringUtils.randomAlphanumeric(8);
            member.setSalt(salt);
            member.setPassword(PasswordUtil.encrypt(member.getUsername(), salt, member.getSalt()));
            member.setDelFlag(false);
            member.setStatus(1);
            userService.save(member);
            //这里处理改为pi_info表信息为准
            PiInfo piInfo = new PiInfo();
            piInfo.setUserId(substring);
            vo.setId(substring);
            piInfo.setPhone(username);
            piInfo.setUsername(username);
            piInfo.setCreateTime(DateTime.now());
            piInfo.setCreateBy(substring);
            piInfo.setDelFlag(false);
            piInfo.setRoleType(vo.getRoleType() + ",");
            piInfo.setPhotoId("defaultPic");
            piInfo.setBanFlag(false);
            piInfoService.save(piInfo);
            // 用户基本信息放置缓存，用于验证是否需要填写基本信息
            redisTemplate.opsForValue().set("FINSH_PIINFO_CODE" + substring, piInfo);

            //若是个人用户创建简历等信息
            boolean roteType = "0".equals(vo.getRoleType());
            if (roteType) {
                //自动创建中文简历
                this.createUser(member.getId());
            }
        } else {
            String memberId = member.getId();
            PiInfo piInfo = piInfoService.lambdaQuery()
                .eq(PiInfo::getUserId, memberId)
                .eq(PiInfo::getDelFlag, false)
                .one();
            //历史遗留
            if (null == piInfo) {
                piInfo = new PiInfo();
                piInfo.setUserId(memberId);
                vo.setId(memberId);
                piInfo.setPhone(username);
                piInfo.setUsername(username);
                piInfo.setCreateTime(DateTime.now());
                piInfo.setCreateBy(memberId);
                piInfo.setDelFlag(false);
                piInfo.setRoleType(vo.getRoleType() + ",");
                piInfo.setPhotoId("defaultPic");
                piInfo.setBanFlag(false);
                piInfoService.save(piInfo);
                redisTemplate.opsForValue().set("FINSH_PIINFO_CODE" + memberId, piInfo);
                this.createUser(memberId);
            } else {
                vo.setId(piInfo.getUserId());
                String roleType = piInfo.getRoleType();
                //历史遗留，暂无用处
                if (StrUtil.isBlank(roleType)) {
                    Assert.isTrue(false, "当前账号异常，请联系管理员进行处理");
                }
                //历史遗留，暂无用处 不包含已存在用户得角色，如果是个人用户则需创建简历部分
                if (!roleType.contains(vo.getRoleType())) {
                    String[] split = roleType.split(",");
                    for (String role : split) {
                        //说明是企业用户到个人用户去注册
                        if (!StrUtil.equals("0", role) && StrUtil.equals("0", vo.getRoleType())) {
                            //自动创建中文简历
                            String s = roleType + vo.getRoleType() + ",";
                            piInfo.setRoleType(s);
                            piInfoService.updateById(piInfo);
                            redisTemplate.opsForValue().set("FINSH_PIINFO_CODE" + memberId, piInfo);
                            this.createUser(memberId);
                            break;
                        }
                    }
                }
            }
            userService.updateById(member);
        }

        /********初步看 2021年1月22日10:04:10 暂无意义 begin ******/
        List<SysUserDepart> count = userDepartService.lambdaQuery().eq(SysUserDepart::getUserId, vo.getId()).list();
        if (CollectionUtils.isEmpty(count)) {
            vo.setReg(false);
        } else {
            String id = count.get(0).getDepId();
            int departInfo = enInfoService.lambdaQuery().eq(EnInfo::getId, id).eq(EnInfo::getDelFlag, false).count();
            vo.setReg(departInfo != 0);
        }
        /********初步看 2021年1月22日10:04:10 暂无意义 end ******/

        LambdaQueryWrapper<PiInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PiInfo::getUserId, member.getId()).eq(PiInfo::getDelFlag, false);
        PiInfo piInfo = piInfoService.getOne(wrapper);
        Assert.isFalse(piInfo.getBanFlag(), "当前账号已被禁用，请联系相关客服进行处理");
        //普通登录及微信扫描绑定时需要验证验证码
        if (this.loginType.equalsIgnoreCase(Constant.LOGIN_TYPE_SMSCODE) || this.loginType.equalsIgnoreCase(Constant.LOGIN_TYPE_WX_LOGIN_BIND)) {
            //2021年1月22日11:56:04 新增扫描登录逻辑
            if (!StrUtil.equals(profiles, TEST_2)) {
                log.info("==============>开始验证短信、验证码");
                String code = (String) redisTemplate.opsForValue().get("SEND_VERIFY_CODE_PERSON_:" + getUsername());
                if (StringUtils.isBlank(code)) {
                    Assert.isTrue(false, "验证码错误");
                }
                Assert.isTrue(StrUtil.equals(password, code), "验证码错误");
                redisTemplate.delete(CommonConstant.SEND_VERIFY_CODE + username);
            }
        }

        member.setBanFlag(piInfo.getBanFlag());
        return member;

    }

    public void createUser(String memberId) {
        //初始化简历表
        SysUser user = this.userService.getById(memberId);
        CvResume resume = new CvResume();
        String cv = UuidUtils.getUUID().substring(0, 32);
        resume.setId(cv);
        resume.setResumeName(StrUtil.sub(user.getPhone(), user.getPhone().length(), -4) + "的中文简历");
        resume.setCreateTime(DateTime.now());
        resume.setCreateBy(memberId);
        resume.setDelFlag(false);
        resume.setType(0);
        resume.setLanType(0);
        resume.setBrowseCount(0);
        resume.setUserId(memberId);
        cvResumeService.save(resume);
        //设置简历id
        vo.setResumId(cv);
    }

    @Override
    public void success(SysUser user) {
        vo.setId(user.getId());
        vo.setMobile(user.getPhone());
        vo.setUsername(user.getUsername());
        vo.setVip(true);
        vo.setDesc("");
        vo.setToken(super.token);

        user.setToken(super.token);
        userService.updateById(user);
    }
}